package cjq.demo.util;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Map;

/**
 * 自定义的http工具类
 * author: cjianquan
 * date: 2017/2/22
 */
public class CustHttpUtils {

    private final static Logger logger = Logger.getLogger(CustHttpUtils.class);


    /**
     * 用流的方式获取html
     * cjianquan 2016/12/27
     * @param url
     * @param cookies
     * @param headData
     * 对于头部有如下属性示例：
     * headData.put("Host","www.qichacha.com");
     * headData.put("Accept","*\*");  //这里的"\"实际为"/"
     * headData.put("Referer","http://www.qichacha.com/");
     * headData.put("X-Requested-With","XMLHttpRequest");
     * headData.put("Origin","http://www.qichacha.com");
     * headData.put("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
     * headData.put("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13E238 MicroMessenger/6.3.16 NetType/WIFI Language/zh_CN");
     * @return
     */
    public static String doGetByStream(String url,Cookie[] cookies,Map<String,String> headData){
        GetMethod method = new GetMethod(url);
        return getResponseByStream(method,cookies,headData);
    }

    /**
     * 该方法用于解决如下的提示：
     * Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.
     * cjianquan 2016/12/27
     * @param httpMethod
     * @param cookies
     * @param headData
     * @return
     */
    private static String getResponseByStream(HttpMethod httpMethod,Cookie[] cookies,Map<String,String> headData){
        // 构造HttpClient的实例
        String result = null;
        org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
        if(cookies!=null){
            httpClient.getState().addCookies(cookies);
        }
        if(headData!=null && !headData.isEmpty()){
            for(String key : headData.keySet()){
                String value = headData.get(key);
                httpMethod.addRequestHeader(key,value);
            }
        }
        httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        try {
            int statusCode = httpClient.executeMethod(httpMethod);
            if (statusCode != HttpStatus.SC_OK) {
                logger.info("[getResponse]Method failed: " + httpMethod.getStatusLine());
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(httpMethod.getResponseBodyAsStream(),"UTF-8"));
            StringBuffer stringBuffer = new StringBuffer();
            String str = "";
            while((str = reader.readLine())!=null){
                stringBuffer.append(str);
            }
            result = stringBuffer.toString();

        } catch (Exception e) {
            logger.error("[getResponse]has error",e);
        } finally {
            httpMethod.releaseConnection();
        }
        return result;
    }

}
